import logging
import time

from api.service.rule_template_service import RULE_GRAPH_TEMPLATES
from jinja2 import Template
import json

logger = logging.getLogger(__name__)


def transform_rule_to_workflow(input_data):
    match_start = time.perf_counter()
    # Jinja2 模板对象
    template = Template(RULE_GRAPH_TEMPLATES["rule"]["graph"]["trigger"])

    # 渲染模板
    output_json_str = template.render(
        rule_code=input_data.get("rule_code", "UNKNOWN"),
        conditions_group=input_data.get("conditions_group", {}),
        results=input_data.get("results", {}),
        attrType=input_data.get("attrType", "basicsSingle"),
        error_message=input_data.get("error_message", "")
    )
    print(output_json_str)
    # 格式化为标准 JSON
    output_data = json.loads(output_json_str)
    match_elapsed = time.perf_counter() - match_start
    # 转换为毫秒
    match_elapsed_ms = match_elapsed * 1000
    logger.info(f"耗时: {match_elapsed_ms:.4f} ms")  # 保留4位小数，单位毫秒

    return output_data


def transform_rule_to_result(input_data):
    match_start = time.perf_counter()
    # Jinja2 模板对象
    template = Template(RULE_GRAPH_TEMPLATES["rule"]["graph"]["answer"])

    # 渲染模板
    output_json_str = template.render(
        rule_code=input_data.get("rule_code", "UNKNOWN"),
        conditions_group=input_data.get("conditions_group", {}),
        results=input_data.get("results", {}),
        error_message=input_data.get("error_message", "")
    )
    # 格式化为标准 JSON
    output_data = json.loads(output_json_str)
    match_elapsed = time.perf_counter() - match_start
    # 转换为毫秒
    match_elapsed_ms = match_elapsed * 1000
    logger.info(f"耗时: {match_elapsed_ms:.4f} ms")  # 保留4位小数，单位毫秒
    return output_data


def transform_result(rule_data, answer, fact, rule_result):
    data = transform_facts(rule_result, fact)
    if len(data) == 0:
        return None
    return {
        "rule_code": rule_data.get("rule_code"),
        "attr_type": rule_data.get("attr_type"),
        "description": rule_data.get("description"),
        "reason": transform_reason_str(data),
        'no_matchs': data,
        "error_message": answer,
        "error_code": rule_data.get("error_code")
    }


def transform_facts(rule_results, fact):
    values = []
    for item in rule_results:
        if not item.get("match_result"):
            values.append(
                {"field_name": item.get("variable_selector")[1],
                 "field_value": item.get("actual_value"),
                 "operator": item.get("comparison_operator"),
                 "match_result": item.get("match_result"),
                 "recommend_value": item.get("expected_value")}
            )
    return values


def transform_reason_str(data):
    output_str = ""
    for item in data:
        output_str += f"字段名：{item['field_name']}，比较符：{item['operator']}，推荐值：{item['recommend_value']}，真实值：{item['field_value']};"
    return output_str
